const ws = require('nodejs-websocket');
const log = require('../utils/log');
const Cmd = require('../config/Cmd');
const Stype = require('../config/Stype');
const game_config = require('../config/game_config');

const hallDb = require('./hallDb')
const hallRedis = require('./hallRedis')
const ResCode = require("../config/ResCode");

const dt = require('../proto/DT');
// const hallPro = require("./proto/Hall.proto");
const msgCfg = require('../common/MsgCfg');
const GameCfg = require('../config/gameCfg');
const hallModel = require('./hallModel');
const hallNewReward = require('./hallNewReward');
const hallZt = require('./gameZt/hallZt');
const GameZtInfo = require('./gameZt/game_tz_info');
const {Respones} = require("../config/gameCfg");
const HallTz = require("./gameTz/hallTz");
const CmdHall = require('./proto/CmdHall');
const redisBase = require("../common/RedisBase");

const hall = require('./hall/hall');
const hdchoujiang = require('./hd_choujiang/hdchoujiang');


class hallMessageMgr{
    constructor(){

    }

    static getInstance(){
        if(!hallMessageMgr.instance){
            hallMessageMgr.instance = new hallMessageMgr();
            return hallMessageMgr.instance;
        }else{
            return hallMessageMgr.instance;
        }
    }

    connectServer(port){
        log.info('=======connectServer==hall=========',port);
        let websocket = ws.createServer((client)=>{
            log.info('====收到客户端发送的消息=====');
            //收到的是json 数据
            client.on('text',(result)=>{
                log.warn('====收到客户端发送的消息=text=====');
                this.proto_type = msgCfg.PROTOTYPE.PROTO_JSON;
                this.decodeJson(result,client);
            });

            client.on('error',(err)=>{
                log.error('=======链接出现错误=========',err.code);
            });

            client.on('close',()=>{
                let uid = client.pathname;
                log.error('=======链接断开大厅服务 用户uid = ', uid);
                if(uid){
                    hallZt.theme_match_discannect_clear_roomInfo(uid);
                }
            });

            client.on('connection',(conn)=>{
                log.error('=======connection=========');
            });

            client.on('listening',(conn)=>{
                log.error('=======listening=========');
            })
        })
        websocket.listen(port);
        console.log('《大厅》服务端正在运行');
    }

    //解析json协议
    decodeJson(result,client){
        let msg = JSON.parse(result);
        let ctype = msg.type;
        let data = msg.data;
        log.info('======decodeJson========',ctype,data);
        this.recvMessage(ctype,data, client);
    }

    //接受客户端收到的消息
    recvMessage(ctype, data, client){
        log.info('=========recvMessage==========',ctype);
        switch (ctype) {
            case CmdHall.GetHallReq: //获取大厅配置
                this.onHallReq(data,ctype,client);
                break;
            case CmdHall.GetUserRewardReq: //获取新手奖励数据
                this.onGetNewRewardsReq(data,ctype,client);
                break;
            case CmdHall.GetNewPlayerReq: //领取新用户奖励
                this.onGetNewPlayerReq(data,ctype,client);
                break;
            case CmdHall.GetUserInfoReq: //用户基本信息
                this.onGetUserInfoReq(data,ctype,client);
                break;

            case CmdHall.GetHD5_PrizeDrawListReq: //幸运抽奖配置
                this.onHDChouJiangCfg(data,ctype,client);
                break;
            case CmdHall.GetHD5_PrizeDrawOptReq: //幸运抽奖操作
                this.onHDChouJiangOpt(data,ctype,client);
                break;

            case CmdHall.GetHD_LoginRewardReq: //每周登录奖励
                this.onHDWeeklyRewardCfg(data,ctype,client);
                break;

            case CmdHall.ThemeMatchReq: //主题赛配置
                this.onThemeMatchReq(data,ctype,client);
                break;
            case CmdHall.ThemeMatchPPReq: //主题赛开始匹配（创建房间）
                this.onThemeMatchPPReq(data,ctype,client);
                break;
            case CmdHall.ThemeMatchPPStopReq: //主题赛停止匹配（离开房间）
                this.onThemeMatchPPStopReq(data,ctype,client);
                break;


            case CmdHall.DailyChallengeCfgReq: //每日挑战配置
                this.onDailyChallengeCfgReq(data,ctype,client);
                break;
            case CmdHall.DailyChallengeReq: //每日挑战选择 大神和休闲
                this.onDailyChallengeReq(data,ctype,client);
                break;
            case CmdHall.GamePlayTzReq: //每日挑战开始游戏
                this.onGamePlayTzReq(data,ctype,client);
                break;
            case CmdHall.GameTzAddCountReq: //看广告添加挑战次数或者复活次数
                this.onGameTzAddCountReq(data,ctype,client);
                break;
            default:
                break;
        }
    }

    sendMessage(data, client){
        if(this.proto_type === msgCfg.PROTOTYPE.PROTO_BINARY){
            log.error('======sendMessage binary=======',data);
            client.sendBinary(data);
        }else if(this.proto_type === msgCfg.PROTOTYPE.PROTO_JSON){
            log.error('======sendMessage JSON=======',data.type);
            client.send(JSON.stringify(data));
        }
    }

    //大厅消息请求
    async onHallReq(data,ctype, client){
        log.warn('=========onHallReq=========',data.userId);
        client.pathname = data.userId;
        await hall.getHallRes(data,ctype,client);
    }

    //获取新手奖励数据
    onGetNewRewardsReq(data,type,client){
        let ret = hallNewReward.getNewRewards(type);
        log.info('=======onGetNewRewardsReq======',ret)
        this.sendMessage(ret,client);
    }

    //领取新手奖励
    async onGetNewPlayerReq(data, ctype,client){
        log.info('=========onGetNewPlayerReq=========',data);
        let res = await hallNewReward.get_new_player_reward(data,ctype,client);
        this.sendMessage(res,client);
    }

    //用户的基础信息
    async onGetUserInfoReq(data,ctype,client){
        await hall.getUserInfo(data,ctype,client);
    }

    // 活动----幸运抽奖配置
    async onHDChouJiangCfg(data,ctype,client){
        await hdchoujiang.getChouJiangCfg(data,ctype,client);
    }
    // 活动----幸运抽奖操作
    async onHDChouJiangOpt(data,ctype,client){
        await hdchoujiang.getChouJiangOpt(data,ctype,client);
    }

    //活动----每周登录奖励 配置
    async onHDWeeklyRewardCfg(data,ctype,client){
        // await hdWeekly
    }

    //降序，按
    sortByLvAndXzNum(a, b) {
        if(a.dwLv !== b.dwLv ){
            return b.dwLv - a.dwLv;
        }else{
            return b.dwXzNum - a.dwXzNum;
        }
    }

    //主题赛配置
    async onThemeMatchReq(data,type,client){
        log.info('=========onThemeMatchReq=========',data);
        let uid = data.userId;

        await hallZt.addGameInfoToRedis(uid);

        let gameList = await redisBase.getGameListZt();
        log.info('=========gameList========',gameList.length);

        // 获取主题赛的数据
        let myInfo = [];
        let arrWt = [];
        let arrZq = [];
        let arrMz = [];

        if(gameList){
            for (let i = 0; i < gameList.length; i++) {
                let cfgCur = JSON.parse(gameList[i]);
                if(cfgCur.uid === uid){
                    myInfo.push(cfgCur);
                }
                if(cfgCur.gamType === GameCfg.DWTYPE.DW_WENTI){
                    arrWt.push(cfgCur);
                }else if(cfgCur.gamType === GameCfg.DWTYPE.DW_ZUQIU){
                    arrZq.push(cfgCur);
                }else if(cfgCur.gamType === GameCfg.DWTYPE.DW_MINGZU){
                    arrMz.push(cfgCur);
                }
            }
        }
        arrWt.sort(this.sortByLvAndXzNum);
        arrZq.sort(this.sortByLvAndXzNum);
        arrMz.sort(this.sortByLvAndXzNum);

        let wtArr = arrWt.length > 3 ? arrWt.slice(0,3) : arrWt;
        let zqArr = arrZq.length > 3 ? arrZq.slice(0,3) : arrZq;
        let mzArr = arrMz.length > 3 ? arrMz.slice(0,3) : arrMz;
        log.error("=======myInfo=========",myInfo.length);

        for (let i = 0; i < myInfo.length; i++) {
            let cfg = myInfo[i];
            cfg.users = [];
            if(cfg.gamType === GameCfg.DWTYPE.DW_WENTI){
                cfg.users = wtArr;
            }else if(cfg.gamType === GameCfg.DWTYPE.DW_ZUQIU){
                cfg.users = zqArr;
            }else if(cfg.gamType === GameCfg.DWTYPE.DW_MINGZU){
                cfg.users = mzArr;
            }
        }

        myInfo.sort((a,b)=>{
            return a.gamType - b.gamType;
        })

        if(myInfo.length > 0){
            let res = await hallZt.theme_match_cfg_success(myInfo,type);
            log.error("=======onThemeMatchRes=========",uid);
            this.sendMessage(res,client);
        }

        await redisBase.closeRedis()
    }

    // 主题赛开始匹配（创建房间）
    async onThemeMatchPPReq(data,ctype, client){
        log.info('=========onThemeMatchPPReq=========',data);
        let res= await hallZt.theme_match_start_pp(data,client,ctype);
        this.sendMessage(res,client);
        redisBase.closeRedis();
    }

    //主题赛停止匹配
    async onThemeMatchPPStopReq(data,ctype,client){
        log.info('========onThemeMatchPPStopReq======',data);
       let res = await hallZt.theme_match_stop_pp(data,ctype);
       log.info('=====onThemeMatchPPStopReq========',res);
       this.sendMessage(res,client);
        redisBase.closeRedis();
    }


    //每日挑战配置
    async onDailyChallengeCfgReq(data,ctype,client){
        log.info('=======onDailyChallengeCfgReq=======',data);
        await HallTz.mrtz_game_cfg(data,ctype,client);
    }

    // 每日挑战选择 大神和休闲
    async onDailyChallengeReq(data,ctype,client){
        log.info('=======onDailyChallengeReq=======',data);
        await HallTz.mrtz_game_choice(data,ctype,client);
    }

    // 每日挑战开始游戏
    async onGamePlayTzReq(data,ctype,client){
        log.info('=======onGamePlayTzReq=======',data);
        await HallTz.mrtz_game_start(data,ctype,client);
    }

    // 看广告添加挑战次数或者复活次数
    async onGameTzAddCountReq(data,ctype,client){
        log.info('=======onGameTzAddCountReq=======',data);
        await HallTz.mrtz_game_add_count(data,ctype,client);
    }
}

module.exports = hallMessageMgr.getInstance();